package com.todod.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.todod.annotaion.NotLogging;
import com.todod.exception.LoginExpiredException;
import com.todod.exception.LoginOutException;

import cn.dev33.satoken.stp.StpUtil;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (handler instanceof HandlerMethod) {
			HandlerMethod hm = (HandlerMethod) handler;
			Method m = hm.getMethod();

			if (m.isAnnotationPresent(NotLogging.class)) { // 不需登陆
				return true;
			}

			// 需要登陆
//			String token = request.getHeader("X-Token"); // 取得token
//
//			if (StringUtils.isBlank(token)) {
//				throw new LoginOutException("未登录");
//			}
			try {
				// 校验token
//				String userId = EncryptUtil.decrypt(token);

				if (StpUtil.isLogin()) {
					request.setAttribute("_userId", StpUtil.getLoginId());// 添加用户id
					return true;
				} else {
					throw new LoginOutException("未登录");
				}
			} catch (Exception e) {
				throw new LoginExpiredException("登陆过期");
			}
		}

		return true;
	}
}
